﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class skillBook : MonoBehaviour
{
    private static skillBook instance;
    public static skillBook MyInstance
    {
        get
        {
            if (instance == null)
            {
                instance = FindObjectOfType<skillBook>();
            }
            return instance;
        }
    }

    public Spell[] MySpells { get => spells; set => spells = value; }

    [SerializeField]
    private Spell[] spells;

    [SerializeField]
    private Text skillName;

    [SerializeField]
    private Image skillbar;

    [SerializeField]
    private Image skillIcon;

    private Coroutine spellrutine;
    private Coroutine appearutine;
    [SerializeField]
    private Text castTimer;

    [SerializeField]
    private CanvasGroup canvasgrp;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        
    }
    public void useSpell(ICastable castable)
    {
        skillbar.fillAmount = 0;   
        spellrutine = StartCoroutine(castProgress(castable));
        appearutine= StartCoroutine(appear());
        skillName.text = castable.MyTitle;
        skillbar.color = castable.MyBarColour;
        skillIcon.sprite = castable.MyIcon;
    }
    private IEnumerator castProgress(ICastable castable)
    {
 
        //float timer;
        float timePassed=Time.deltaTime;
        float fillSpd=1.0f/ castable.MyCastTime;
        float fill = 0;
        while (fill <= 1.0f)
        {
            castTimer.text =(castable.MyCastTime - timePassed).ToString("F1");
            timePassed += Time.deltaTime;
            skillbar.fillAmount = Mathf.Lerp(0, 1 , fill );
            fill += fillSpd * Time.deltaTime;
            yield return null;
        }
        stopCast();
        
    }
    public void stopCast()
    {
        if(spellrutine !=null)
        {
            StopCoroutine(spellrutine);
            spellrutine = null;
        }
        if(appearutine != null)
        {
            StopCoroutine(appearutine);
            canvasgrp.alpha = 0;
        }

    }
    private IEnumerator appear()
    {

        //float timer;

        float fillSpd = 1.0f / 0.5f;
        float fill = 0;
        while (fill <= 1.0f)
        {
            canvasgrp.alpha = Mathf.Lerp(0, 1, fillSpd);
            fill += fillSpd * Time.deltaTime;
            yield return null;
        }

    }
    public Spell getSkill(string spellname) {
        Spell tempspell = Array.Find(MySpells, x => x.MyTitle == spellname);
        return tempspell;
    }
}
